// 生成条形码页面 - iOS风格 - 混合生成版本（服务器端+本地生成）
const apiService = require('../../utils/api-service.js');
const MessageUtil = require('../../utils/message-util.js');

Page({
  data: {
    // 基础数据
    inputContent: '',
    batchContent: '',
    batchMode: false,
    batchLines: 0,
    
    // 条形码类型
    barcodeType: 'Code 128',
    
    // 限制设置
    maxLength: 100,
    maxBatchLength: 2000,
    
    // 美化选项
    foregroundColor: '#000000',
    backgroundColor: '#ffffff',
    barcodeWidth: 300,
    
    // 状态控制
    generating: false,
    
    // 离线模式状态
    isOfflineMode: false
  },

  onLoad(options) {
    // 从参数中获取类型信息
    if (options.type) {
      const type = decodeURIComponent(options.type);
      this.setData({ barcodeType: type });
      this.adjustLimits();
    }
    
    // 检查离线模式
    this.checkOfflineMode();
  },

  onShow() {
    // 页面显示时重新检查离线状态
    this.checkOfflineMode();
  },

  // 检查离线模式状态
  checkOfflineMode() {
    try {
      const app = getApp();
      const isOffline = app.isOfflineMode();
      
      this.setData({
        isOfflineMode: isOffline
      });
      
      console.log('条形码生成页面 - 离线模式状态:', isOffline);
    } catch (error) {
      console.error('检查离线模式失败:', error);
      this.setData({
        isOfflineMode: false
      });
    }
  },

  // 切换批量模式
  toggleBatchMode() {
    const newBatchMode = !this.data.batchMode;
    this.setData({ 
      batchMode: newBatchMode,
      inputContent: '',
      batchContent: '',
      batchLines: 0
    });
  },

  // 单个输入变化
  onInputChange(e) {
    const value = e.detail.value;
    this.setData({ inputContent: value });
    this.validateInput(value);
  },

  // 批量输入变化
  onBatchInputChange(e) {
    const value = e.detail.value;
    const lines = value.split('\n').filter(line => line.trim()).length;
    
    // 限制行数
    if (lines > 50) {
      const limitedLines = value.split('\n').slice(0, 50).join('\n');
      this.setData({ 
        batchContent: limitedLines,
        batchLines: 50
      });
      wx.showToast({
        title: '最多支持50行',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ 
      batchContent: value,
      batchLines: lines
    });
  },

  // 切换条形码类型
  switchType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ barcodeType: type });
    this.adjustLimits();
    
    // 重新验证当前输入
    if (!this.data.batchMode && this.data.inputContent) {
      this.validateInput(this.data.inputContent);
    }
  },

  // 根据类型调整输入限制
  adjustLimits() {
    let maxLength = 100;
    
    switch (this.data.barcodeType) {
      case 'EAN-13':
        maxLength = 13;
        break;
      case 'EAN-8':
        maxLength = 8;
        break;
      case 'Code 39':
        maxLength = 80;
        break;
      case 'ITF':
        maxLength = 50;
        break;
      case 'Code 128':
      default:
        maxLength = 100;
        break;
    }
    
    this.setData({ maxLength });
  },

  // 输入验证
  validateInput(value) {
    const type = this.data.barcodeType;
    
    // 数字格式验证
    if (type === 'EAN-13' || type === 'EAN-8' || type === 'ITF') {
      const numericOnly = value.replace(/[^0-9]/g, '');
      if (numericOnly !== value) {
        this.setData({ inputContent: numericOnly });
      }
    }
    
    // Code 39 字符限制
    if (type === 'Code 39') {
      const validChars = value.replace(/[^A-Z0-9\-. $\/+%]/g, '');
      if (validChars !== value) {
        this.setData({ inputContent: validChars.toUpperCase() });
      }
    }
  },

  // 选择颜色
  selectColor(e) {
    const { type, color } = e.currentTarget.dataset;
    if (type === 'foreground') {
      this.setData({ foregroundColor: color });
    } else if (type === 'background') {
      this.setData({ backgroundColor: color });
    }
  },

  // 选择尺寸
  selectSize(e) {
    const size = parseInt(e.currentTarget.dataset.size);
    this.setData({ barcodeWidth: size });
  },

  // 生成条形码
  async generateBarcode() {
    // 防止重复点击
    if (this.data.generating) return;
    
    // 验证输入
    if (!this.validateBeforeGenerate()) return;
    
    // 开始生成动画
    this.setData({ generating: true });
    
    try {
      await this.performGeneration();
      
    } catch (error) {
      console.error('生成条形码失败:', error);
      MessageUtil.showNetworkError(error);
    } finally {
      // 结束生成动画
      this.setData({ generating: false });
    }
  },

  // 生成前验证
  validateBeforeGenerate() {
    if (this.data.batchMode) {
      if (!this.data.batchContent.trim()) {
        wx.showToast({
          title: '请输入批量内容',
          icon: 'none'
        });
        return false;
      }
      
      const lines = this.data.batchContent.split('\n').filter(line => line.trim());
      if (lines.length === 0) {
        wx.showToast({
          title: '请输入有效内容',
          icon: 'none'
        });
        return false;
      }
      
      // 验证每行内容
      for (let i = 0; i < lines.length; i++) {
        if (!this.validateSingleContent(lines[i].trim())) {
          wx.showToast({
            title: `第${i + 1}行内容格式不正确`,
            icon: 'none'
          });
          return false;
        }
      }
    } else {
      if (!this.data.inputContent.trim()) {
        wx.showToast({
          title: '请输入条形码内容',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.validateSingleContent(this.data.inputContent)) {
        wx.showToast({
          title: '内容格式不正确',
          icon: 'none'
        });
        return false;
      }
    }
    
    return true;
  },

  // 验证单个内容
  validateSingleContent(content) {
    const type = this.data.barcodeType;
    
    switch (type) {
      case 'EAN-13':
        return /^\d{13}$/.test(content);
      case 'EAN-8':
        return /^\d{8}$/.test(content);
      case 'ITF':
        return /^\d+$/.test(content) && content.length % 2 === 0;
      case 'Code 39':
        return /^[A-Z0-9\-. $\/+%]+$/.test(content);
      case 'Code 128':
      default:
        return content.length > 0 && content.length <= this.data.maxLength;
    }
  },

  // 执行生成
  async performGeneration() {
    // 统一跳转到结果页面，由结果页面根据离线状态选择生成方式
    const generateData = {
      content: this.data.batchMode ? 
        this.data.batchContent.split('\n').filter(line => line.trim()) : 
        this.data.inputContent,
      barcodeType: this.data.barcodeType,
      foregroundColor: this.data.foregroundColor,
      backgroundColor: this.data.backgroundColor,
      barcodeWidth: this.data.barcodeWidth,
      batchMode: this.data.batchMode
    };

    // 保存到历史记录
    this.saveToHistory();

    // 跳转到结果页面
    const dataParam = encodeURIComponent(JSON.stringify(generateData));
    wx.navigateTo({
      url: '/pages/generate-result/generate-result?data=' + dataParam
    });
  },



  // 服务器生成条形码
  async generateWithServer() {
    try {
      const content = this.data.batchMode ? 
        this.data.batchContent.split('\n').filter(line => line.trim()) : 
        this.data.inputContent;

      const params = {
        codeType: 'barcode',
        subType: this.data.barcodeType,
        content: content,
        batchMode: this.data.batchMode,
        options: {
          foregroundColor: this.data.foregroundColor,
          backgroundColor: this.data.backgroundColor,
          size: this.data.barcodeWidth
        }
      };

      // 调用API服务
      const response = await apiService.generateCode(params);
      
      // 保存到历史记录
      this.saveToHistory();
      
      if (this.data.batchMode) {
        // 批量生成，保存压缩包
        const saveResult = await apiService.saveBatchResult(response.data);
        // 跳转到结果页面
        wx.navigateTo({
          url: '/pages/generate-result/generate-result?type=batch&path=' + encodeURIComponent(saveResult.path)
        });
      } else {
        // 单个生成，保存图片
        const saveResult = await apiService.saveImageToAlbum(response.data);
        // 跳转到结果页面
        wx.navigateTo({
          url: '/pages/generate-result/generate-result?type=single&path=' + encodeURIComponent(saveResult.path)
        });
      }
    } catch (error) {
      throw error;
    }
  },



  // 保存到历史记录
  saveToHistory() {
    const historyManager = require('../../utils/history-manager.js');
    const timestamp = new Date().getTime();
    
    const data = {
      batchMode: this.data.batchMode,
      batchContent: this.data.batchContent,
      inputContent: this.data.inputContent,
      barcodeType: this.data.barcodeType,
      foregroundColor: this.data.foregroundColor,
      backgroundColor: this.data.backgroundColor,
      barcodeWidth: this.data.barcodeWidth,
      timestamp: timestamp,
      localGenerated: this.data.isOfflineMode
    };
    
    historyManager.saveBarcodeRecord(data);
  },


}); 